<template>
  <div>
    <van-uploader
      v-model="fileList"
      :after-read="afterRead"
      :before-delete="handleDeleteFile"
      :accept="accept"
      :max-size="20 * 1024 * 1024"
      :disabled="disabled"
      multiple
      upload-icon="plus"
      @oversize="oversize"
    />
  </div>
</template>
<script>
import { reactive, toRefs, watch } from 'vue'
import { fileUpload, getSign } from '@/service/upload'
import { lookFile } from '@/config/env.js'
import { Uploader } from 'vant'
import { Toast } from 'vant'
import $localStorage from '@/utils/localStorage.js'

export default {
  name: 'ImageUpload',
  components: {
    [Uploader.name]: Uploader,
  },
  props: {
    value: {
      type: Array,
      default() {
        return []
      },
    },
    disabled: { type: Boolean, default: false },
    fileType: { type: String, default: '' },
    title: { type: String, default: '' },
    maxCount: { type: Number, default: 3 },
    typeIndex: { type: Number, default: null },
    accept: { type: String, default: 'image/png, image/jpeg' },
  },
  emits: ['uploadBack'],
  setup(props, ctx) {
    const state = reactive({
      fileList: [],
      lookFile: lookFile,
      fileServerPrefix: '',
    })
    const afterRead = (file) => {
      if (file instanceof Array) {
        file.forEach((item) => {
          uploadFile(item.file)
        })
      } else {
        uploadFile(file.file)
      }
      // 获取配置信息
      if ($localStorage.get('fileServerPrefix')) {
        state.fileServerPrefix = $localStorage.get('fileServerPrefix')
      } else {
        getSign().then((res) => {
          state.fileServerPrefix = res.data.fileServerPrefix + '/'
          $localStorage.set('fileServerPrefix', state.fileServerPrefix)
        })
      }
    }
    const uploadFile = (file) => {
      var formData = new FormData()
      formData.append('file', file)
      fileUpload(formData)
        .then((res) => {
          if (res.code == 100) {
            let fileRes = res.body.fileResponseData
            fileRes.type = props.fileType
            fileRes.title = props.title

            state.fileList = state.fileList.filter((item) => {
              return !item.file
            })
            state.fileList.push({
              name: fileRes.fileName,
              size: fileRes.fileSize,
              suffix: fileRes.fileType,
              type: fileRes.type,
              url: state.fileServerPrefix + fileRes.filePath,
              filePath: fileRes.filePath,
              title: fileRes.title,
            })

            Toast(`${fileRes.fileName}上传成功`)
            ctx.emit('uploadBack', state.fileList, props.fileType, props.typeIndex)
          } else {
            Toast(`${file.name}${res.msg}`)
          }
        })
        .catch(() => {
          state.fileList.forEach((item, index) => {
            if (item.file && file.name === item.file.name) {
              state.fileList.splice(index, 1)
            }
          })
          ctx.emit('uploadBack', state.fileList, props.fileType, props.typeIndex)
          Toast.fail(`${file.name}上传失败`)
        })
    }
    const oversize = () => {
      Toast.fail('文件大小不能超过 20 MB！')
    }
    // 删除图片
    const handleDeleteFile = (file, { index }) => {
      let list = state.fileList.filter((item, fileIndex) => {
        return fileIndex !== index
      })
      state.fileList = list
      ctx.emit('uploadBack', list, props.fileType, props.typeIndex)
    }

    watch(
      () => props.value,
      (newValue) => {
        state.fileList = newValue
      },
      { immediate: true }
    )

    return {
      ...toRefs(state),
      afterRead,
      oversize,
      uploadFile,
      handleDeleteFile,
    }
  },
}
</script>
<style scoped>
</style>